package com.lixiangfeiyang.recycleritemhelperdemo

import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import java.util.*

/**
 * itemTouchHelper 工具类
 * 水平list 排序
 *
 * isCanDelete 是否侧滑删除
 * adapter
 */
class LinearItemTouchHelperUtil(var isCanDelete:Boolean,var adapter: TextAdapter) {

    private var draggingView: RecyclerView.ViewHolder? = null
    private var isDelete = false

    fun init(): ItemTouchHelper {
        val list = adapter.list
        var itemTouchHelper: ItemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.Callback() {
            override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
                //竖直位移
                var dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN
                //水平
                var swipeFlags = ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
                if (isCanDelete){
                    return makeMovementFlags(dragFlags+ swipeFlags, swipeFlags)
                }else{
                    return makeMovementFlags(dragFlags+ swipeFlags,0)
                }

            }

            override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
                // 获取被拖拽item和目标item的适配器索引（适配器索引是该item对应数据集的索引，getLayoutPosition是当前布局的位置）
                var from = viewHolder.adapterPosition;
                var to = target.adapterPosition;
                // 交换数据集的数据
                Collections.swap(adapter.list, from, to);
                // 通知Adapter更新
                adapter.notifyItemMoved(from, to);
                // 返回true表示item移到了目标位置
                return true;


            }

            // 允许swipe的前提下，当用户滑动ViewHolder触发临界时调用
            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                // 获取滑动的item对应的适配器索引
                var pos = viewHolder.getAdapterPosition();
                // 从数据集移除数据
                adapter.list.remove(pos);
                // 通知Adapter更新
                adapter.notifyItemRemoved(pos);

            }

        })



        return itemTouchHelper;
    }



}